clear all
set maxvar 30000
version 14
capture log close
set more off

****************************************************************************************************
* -----   Customize the paths and options:   ----- 
****************************************************************************************************
*cd  "Data\"
global MY_IN_PATH   "C:\Users\benjamin.balsmeier\Dropbox\Research\REStat\data"
global MY_OUT_PATH  "C:\Users\benjamin.balsmeier\Dropbox\Research\REStat\data"
*global MY_TEMP_PATH "..."

global MY_OUT_FILE  ${MY_OUT_PATH}out.dta
global MY_LOG_FILE  ${MY_OUT_PATH}cr_cyc.log

log using "${MY_LOG_FILE}", text replace
****************************************************************************************************
* import data
*************************************************************************************************

use ${MY_IN_PATH}/nberces.dta, clear

gen out = matcost + vadd

gen ship_def = vship/piship

gen out_d = out/piship

xtset sic year
gen lout_d = l.out_d
gen l2out_d = l2.out_d
gen l3out_d = l3.out_d
keep sic year out_d lout_d l2out_d l3out_d ship_def 


** GDP in t
merge n:1 year using ${MY_IN_PATH}/gdp.dta, 
drop if _merge == 2
drop _merge


xtset sic year
gen out_dgr = log(out_d/l.out_d)

gen rec = 0
replace rec = 1 if out_dgr < 0

gen exp = 0
replace exp = 1 if out_dgr > 0 & out_dgr !=.

gen fyexp = 0
sort sic year
bysort sic (year): replace fyexp = 1 if out_dgr[_n-1] < 0 & out_dgr > 0 & out_dgr !=. & sic[_n-1] == sic

bysort sic (year) : gen expyr = sum(fyexp)
replace expyr = 0 if rec == 1
replace expyr = 0 if out_dgr <= 0

replace expyr = . if expyr == 0 & exp ==1 & out_dgr !=0
* drop first cycles since we do not know when this cylce started

preserve
keep year sic expyr rec exp
forval num = 1(1)18 {
gen ticyc`num' = 0
replace ticyc`num' = 1 if expyr == `num'
}
compress
save ${MY_OUT_PATH}/ind_specific_cyc_sic4_out.dta, replace
restore


reg out_dgr gdpgr_chained2012dollars, robust

gegen sicid = group(sic) 

gen cyc_sic4_out =.

gen l1gdpgr_chained2012dollars = l.gdpgr_chained2012dollars

forval num = 1(1)459 {
reg out_dgr gdpgr_chained2012dollars if sicid == `num', robust
replace cyc_sic4_out = _b[gdpgr_chained2012dollars] if e(sample) == 1
}

sum cyc_sic4_out,d
keep year sic out_d cyc_sic4_out

drop if cyc_sic4_out ==.
duplicates drop sic, force 
keep sic cyc_sic4_out

compress
save ${MY_OUT_PATH}/cyclic_sic4_out_sic_agg.dta, replace
